package com.kingcat.smartchair.utils;

import static android.media.AudioManager.FLAG_PLAY_SOUND;
import static androidx.core.content.ContextCompat.getSystemService;

import android.annotation.SuppressLint;
import android.content.*;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.media.AudioManager;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import com.google.firebase.BuildConfig;
import com.topjohnwu.superuser.Shell;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 设备相关.
 */
public class DeviceUt {

    private static final int SYSTEM_APP_MASK = ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;

    // 獲取UDID
    public static String GetUDID(Context context){
        //return "1b0eadc0c15f437c";
        return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
    }

    // 獲取版本号
    public static String GetVersion(Context context){
        String versionName = "";
        try
        {
            // 获取包管理器对象
            PackageManager packageManager = context.getPackageManager();

            // 获取当前应用的包名
            String packageName = context.getPackageName();

            // 根据包名获取应用信息
            PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);

            // 获取版本
            versionName = packageInfo.versionName;
        }
        catch (Exception e)
        {
            return versionName;
        }

        return versionName;
    }

    // 獲取版本号
    public static String GetSysVersion(Context context){
        return BuildConfig.VERSION_NAME;
    }

    // 獲取所有已安裝的APP信息
    public static List<Map<String, Object>> getInstalledApps(Context context) {
        if (context == null) {
            Log.e("LOG_TAG", "Context is null");
            return new ArrayList<>(0);
        }

        PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> apps = packageManager.getInstalledPackages(0);
        List<Map<String, Object>> installedApps = new ArrayList<>(apps.size());

        for (PackageInfo packageInfo : apps) {

            // 排除系统APP
            if((packageInfo.applicationInfo.flags & SYSTEM_APP_MASK) != 0)
            {
                continue;
            }

            // 提取安装包信息
            Map<String, Object> map = new HashMap<>();
            map.put("app_name", packageInfo.applicationInfo.loadLabel(packageManager).toString());
            map.put("apk_file_path", packageInfo.applicationInfo.sourceDir);
            map.put("package_name", packageInfo.packageName);
            map.put("version_code", packageInfo.getLongVersionCode());
            map.put("version_name", packageInfo.versionName);
            map.put("data_dir", packageInfo.applicationInfo.dataDir);
            map.put("system_app", (packageInfo.applicationInfo.flags & SYSTEM_APP_MASK) != 0);
            map.put("install_time", packageInfo.firstInstallTime);
            map.put("update_time", packageInfo.lastUpdateTime);
            map.put("is_enabled", packageInfo.applicationInfo.enabled);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                map.put("category", packageInfo.applicationInfo.category);
            }

            installedApps.add(map);
        }

        return installedApps;
    }

    // 打开某个APP
    public static boolean openPackage(Context context, String packageName) {

        Context pkgContext = null;
        if (context.getPackageName().equals(packageName)) {
            pkgContext = context;
        } else {
            // 创建第三方应用的上下文环境
            try {
                pkgContext = context.createPackageContext(packageName,
                        Context.CONTEXT_IGNORE_SECURITY
                                | Context.CONTEXT_INCLUDE_CODE);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }

        //Activity完整名
        String mainAct = null;
        //根据包名寻找
        PackageManager pkgMag = context.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED|Intent.FLAG_ACTIVITY_NEW_TASK);

        @SuppressLint("WrongConstant") List<ResolveInfo> list = pkgMag.queryIntentActivities(intent,
                PackageManager.GET_ACTIVITIES);
        for (int i = 0; i < list.size(); i++) {
            ResolveInfo info = list.get(i);
            if (info.activityInfo.packageName.equals(packageName)) {
                mainAct = info.activityInfo.name;
                break;
            }
        }
        if (TextUtils.isEmpty(mainAct)) {
            return false;
        }
        intent.setComponent(new ComponentName(packageName, mainAct));

        if (pkgContext != null && intent != null) {
            pkgContext.startActivity(intent);
            return true;
        }
        return false;
    }

    // 关闭除自身外的所有第三方APP
    public static void killAllApp(Context context)
    {
        List<Map<String, Object>> apps = DeviceUt.getInstalledApps(context);
        apps.forEach(app ->{
            String packagename = app.get("package_name").toString();
            if (!packagename.equals("com.kingcat.smartchair"))
            {
                // 杀掉启动的第三方APP
                DeviceUt.rootCall("am force-stop " + packagename);
                DeviceUt.rootCall("ps | grep '" + packagename + "' | awk '{print $2}' | xargs kill -9");
            }
        });
    }

    // 执行ROOT 命令
    public static void rootCall(String command)
    {
        List<String> resultText = Shell.cmd(command).exec().getOut();
        StringBuilder stringBuilder =new StringBuilder();
        for(String data : resultText){
            stringBuilder.append(data);
            stringBuilder.append("\n");
        }
        String res = String.format("%s",stringBuilder);
    }


    /**
     * 声音处理
     */
    public static void setVolume(Context context, String volumes) {
        int ADJUST_RAISE = -100;
        try {
            AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
            int max = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            int current = am.getStreamVolume(AudioManager.STREAM_MUSIC);
            float zhanbi = max / 100f;

            Log.i("include_volume:MUSIC 1", "本机最大值=" + max + " 本机当前值=" + current + " 最大音量占比=" + zhanbi + "后台传入的声音值=" + volumes);
            if (!volumes.equals(0)) {
                //转换声音量值
                int apiVolume = Integer.parseInt(volumes);
                //默认值*最大音量占比取整数
                int setapi = (int) (apiVolume * zhanbi);
                Log.i("include_volume:MUSIC 2", "最后正确需要调节到音量为=" + setapi);
                am.setStreamVolume(AudioManager.STREAM_MUSIC, setapi, AudioManager.FLAG_PLAY_SOUND);
                //am.setStreamVolume(AudioManager.STREAM_MUSIC, setapi, AudioManager.FLAG_SHOW_UI);

            } else {
                Log.i("setVolume", "include_volume:设置设备为静音");
                am.setStreamVolume(AudioManager.STREAM_MUSIC, 0, AudioManager.FLAG_PLAY_SOUND);
            }
        } catch (Exception e) {
            Log.e("setVolume", "include_volume:出问题了" + e.getMessage());
        }
    }
}
